<template>
  <div class="app-container">
    <Header navTitle="购物车"></Header>
    <Goods 
    v-for="item in goodsList" 
    :key="item.id" 
    :title="item.goods_name" 
    :price="item.goods_price" 
    :img="item.goods_img" 
    :state="item.goods_state"
    :id="item.id"
    :count="item.goods_count"
    @stateChange="getStateChange"></Goods>
    <Footer :state="fullState" @full-state="getFullState" :amt="amt" :all="total"></Footer>
    <!-- <h1>App 根组件</h1> -->
  </div>
</template>

<script>
import Header from '@/components/Header/Header.vue'
import Goods from '@/components/Goods/Goods.vue'
import Footer from '@/components/Footer/Footer.vue'
import bus from'@/components/eventBus.js'
export default {
  components:{
    Header,
    Goods,
    Footer
  },
  data(){
    return {
      // 商品列表数据
      goodsList:[]

    }
  },
  created(){
    this.getGoods()
    bus.$on('share',(val)=>{
      console.log(val);
      this.goodsList.some(item=>{
        if(item.id === val.id){
          item.goods_count = val.value
          return true
        }
      })
    }) 
  },
  computed:{
    //全选状态的值
    fullState(){
      return this.goodsList.every(item=>item.goods_state)
    },
    //勾选的商品的累积价格
    //先用过滤器过滤已选中的商品，再同数组的reduce累加，
    //reduce((累加的值，循环项)=>{},初始值) 
    amt(){
      return this.goodsList.filter(item => item.goods_state).reduce((total,item)=>{
        return total+= item.goods_price * item.goods_count
      },0)
    },
    // 勾选的商品的总数量
    total(){
      return this.goodsList.filter(item => item.goods_state).reduce((t,item)=>{
        return t += item.goods_count
      },0)
    }
  },
  methods:{
    //获取商品列表数据
    async getGoods(){
      const {data:res} = await this.$axios.get('https://www.escook.cn/api/cart')
      console.log(res);
      this.goodsList = res.list
    },
    //获取最新的state状态
   getStateChange(val){
     this.goodsList.some(item =>{
       if(item.id == val.id){
         item.goods_state = val.newState
         return true
       }
     })
   },
   //使商品的每一项全选中状态
   getFullState(val){
     this.goodsList.forEach(item =>{
       item.goods_state = val
     })
   }

  }
}
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
